import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import style from './p.less';
import { FormInstance } from 'antd/lib/form';
import {
  Modal,
  Button,
  message,
  Input,
  Row,
  Col,
  Form,
  Card,
  Popconfirm,
  Upload,
  Tooltip,
} from 'antd';
import { styleRequired } from '../../../support/constant/common.js';
import { getToken } from '../../../utils/utils';
import { comUploadFn, getCountFn, handFilter } from './variable';
import { getMd5 } from '@/utils/utils';
import { getOptAuthHeaders } from '@/utils/common';

const FormItem = Form.Item;
const mapStateToProps = (state: any) => ({
  audienceList: state.audienceList,
  loading: state.loading.effects['audienceList/postObjWithRes'],
});
class AudienceAddModal extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();

  constructor(props: any) {
    super(props);
    this.state = {
      whiteList: [],
      vinBI: [],
      vinWhite: [],
      vinBlack: [],
      buttonLoading: false,
      vinFileUrl: '',
      btnLoading: {},
    };
  }
  randomNum = Math.random();

  componentDidMount() {
    this.props.onRef(this);
  }

  setData = record => {
    setTimeout(() => {
      const fillFileds = {
        objectGroupName: record.objectGroupName,
        // vinTotal: record.vinTotal,
      };
      this.formRef.current?.setFieldsValue(fillFileds);
    }, 10);

    const { list } = record;
    const obj = getCountFn(list);

    this.setState({
      ...obj,
      recordObj: record,
      isExportBtn: true,
      // vinTotal:list.length
    });
  };

  getLabel = (lable: any) => (
    <span>
      <span style={styleRequired}>*</span>
      {lable}
    </span>
  );

  submitForm = () => {
    this.formRef.current?.submit();
  };

  ok = (values: any) => {
    const { dispatch } = this.props;
    const { vinBI, vinWhite, vinBlack } = this.state;
    const fileList = [...vinBI, ...vinWhite, ...vinBlack];
    if (fileList.length < 1) {
      message.error('受众对象组名单不能为空');
      return false;
    }
    dispatch({
      type: 'audienceList/postObjWithRes',
      payload: {
        url: '/audience/group/save',
        fileList,
        objectGroupName: values.objectGroupName,
        // objectGroupName: '受众对象名字',
        // operator: '操作人',
        // projectId: '项目id',
      },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          this.close();
          message.success('新增成功');
          dispatch({
            type: 'audienceList/postFetchPage',
            payload: { url: '/audience/group/page' },
          });
        }
      },
    });
  };

  close = () => {
    const { closeModal } = this.props;
    closeModal();
    this.formRef.current?.resetFields();
    this.setState({
      whiteList: [],
      vinBI: [],
      vinWhite: [],
      vinBlack: [],
      buttonLoading: false,
      vinFileUrl: '',
    });
  };

  handleUploadVinBI = (info: any) => {
    this.comUploadFn(info, 'vinBI');
  };

  handleUploadVinWhite = (info: any) => {
    this.comUploadFn(info, 'vinWhite');
  };

  handleUploadVinBlack = (info: any) => {
    this.comUploadFn(info, 'vinBlack');
  };

  comUploadFn = (info: any, val: string) => {
    comUploadFn.call(this, info, val);
  };

  render() {
    const { modalVisible, loading, vinFileUrl, filterUrl } = this.props;
    const { vinBI, vinWhite, vinBlack, buttonLoading, btnLoading } = this.state;
    const domain = window.g.url;
    const vinUrl = '/upload/single?bizType=m18';
    const vinStr = `${domain}${vinUrl}`;
    let md5 = getMd5('bizType=m18')

    if (!modalVisible) {
      this.randomNum = Math.random();
    }

    const propsVinBI = {
      action: vinStr,
      onChange: this.handleUploadVinBI,
      multiple: false,
      headers: { OptAuthorization: `${getToken()}`, ...getOptAuthHeaders(),shaSign: md5, },
      maxCount: 1,
      key: this.randomNum,
      openFileDialogOnClick: !btnLoading?.vinBI,
    };
    const propsVinWhite = {
      action: vinStr,
      onChange: this.handleUploadVinWhite,
      multiple: false,
      headers: { OptAuthorization: `${getToken()}`, ...getOptAuthHeaders(),shaSign: md5, },
      maxCount: 1,
      key: this.randomNum + 1,
      openFileDialogOnClick: !btnLoading?.vinWhite,
    };
    const propsVinBlack = {
      action: vinStr,
      onChange: this.handleUploadVinBlack,
      multiple: false,
      headers: { OptAuthorization: `${getToken()}`, ...getOptAuthHeaders(), shaSign: md5, },
      maxCount: 1,
      key: this.randomNum + 2,
      openFileDialogOnClick: !btnLoading?.vinBlack,
    };
    const footer = (
      <div>
        <Button size="small" onClick={this.close}>
          取消
        </Button>
        <Button size="small" loading={loading} onClick={this.submitForm} type="primary">
          保存
        </Button>
      </div>
    );
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 16 },
      },
    };
    return (
      <Modal
        style={{ top: 20 }}
        footer={footer}
        title="新增"
        visible={modalVisible}
        onCancel={this.close}
      >
        <Form style={{ marginTop: 12 }} ref={this.formRef} onFinish={this.ok} layout="vertical">
          <FormItem
            {...formItemLayout}
            label="受众对象组名称"
            name="objectGroupName"
            rules={[{ required: true, message: '请输入受众对象组名称' }]}
          >
            <Input placeholder="请输入" />
          </FormItem>
          <span>受众对象组名单</span>
          <div style={{ marginTop: 10 }}>
            <Card bordered={true}>
              <div>
                <Row>
                  <Col span={11}>
                    <span style={{ float: 'left' }}>BI名单（基础）</span>
                    {filterUrl ? (
                      <a title="跳转BI名单筛选" onClick={() => handFilter(this)}>
                        查找筛选
                      </a>
                    ) : (
                      <a disabled title="跳转BI名单筛选">
                        查找筛选
                      </a>
                    )}
                  </Col>
                  <Col span={13} className={style.uploadBox}>
                    <Upload {...propsVinBI} accept=".xlsx,.xls">
                      {
                        <Button loading={btnLoading?.vinBI} type="primary" size="small">
                          导入
                        </Button>
                      }
                    </Upload>
                  </Col>
                </Row>
              </div>
              <div style={{ marginTop: 20 }}>
                <Row>
                  <Col span={11}>
                    <span style={{ float: 'left' }}>白名单（增补）</span>
                    {vinFileUrl === '' ? (
                      <a disabled title="点击下载模板文件">
                        暂无模板下载
                      </a>
                    ) : (
                      <a href={vinFileUrl} title="点击下载模板文件">
                        模板下载
                      </a>
                    )}
                  </Col>
                  <Col span={13} className={style.uploadBox}>
                    <Upload {...propsVinWhite} accept=".xlsx,.xls">
                      {
                        <Button loading={btnLoading?.vinWhite} type="primary" size="small">
                          导入
                        </Button>
                      }
                    </Upload>
                  </Col>
                </Row>
              </div>
              <div style={{ marginTop: 20 }}>
                <Row>
                  <Col span={11}>
                    <span style={{ float: 'left' }}>黑名单（剔除）</span>
                    {vinFileUrl === '' ? (
                      <a disabled title="点击下载模板文件">
                        暂无模板下载
                      </a>
                    ) : (
                      <a href={vinFileUrl} title="点击下载模板文件">
                        模板下载
                      </a>
                    )}
                  </Col>
                  <Col span={13} className={style.uploadBox}>
                    <Upload {...propsVinBlack} accept=".xlsx,.xls">
                      {
                        <Button loading={btnLoading?.vinBlack} type="primary" size="small">
                          导入
                        </Button>
                      }
                    </Upload>
                  </Col>
                </Row>
              </div>
              <div style={{ color: 'gray', marginTop: 20, fontSize: 'small' }}>
                <Row>
                  <Col span={3}>
                    <span>说明：</span>
                  </Col>
                  <Col span={21}>
                    <span>
                      1.受众对象组的对象总数 = BI名单（基础）对象数 + 白名单（增补）对象数 -
                      黑名单（剔除）对象数（当数据有重复时，两者不相等）；
                    </span>
                  </Col>
                </Row>
                <Row>
                  <Col span={3}>
                    <span></span>
                  </Col>
                  <Col span={21}>
                    <span>2.受众对象具有唯一性，不允许重复；</span>
                  </Col>
                </Row>
              </div>
            </Card>
          </div>
        </Form>
      </Modal>
    );
  }
}
export default connect(mapStateToProps)(AudienceAddModal);
